package com.chuantou.yuba.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.CityListTO;
import com.chuantou.yuba.api.to.CityTO;
import com.chuantou.yuba.api.to.GiftTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.ViewHolder;
import com.google.gson.Gson;

public class ExchangeGiftActivity extends BaseActionBarActivity implements OnClickListener {
	private EditText mReceiverView;
	private EditText mPhoneView;
	private TextView mDistrictView;
	private EditText mAddressView;
	private EditText mZipCodeView;
	private List<CityTO> mCities;
	private GiftTO mGift;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mGift = getIntent().getParcelableExtra(Constants.EXTRA_DATA);
		setContentView(R.layout.exchange_gift);
		CityListTO list = parseLocalCity();
		if (list != null) {
			mCities = list.getCities();
		}
		setupViews();
		setTitle(R.string.receiving_information);
	}

	private CityListTO parseLocalCity() {
		try {
			InputStream in = getAssets().open("cities");
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String str = reader.readLine();
			Gson gson = new Gson();
			return gson.fromJson(str, CityListTO.class);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private void setupViews() {
		mReceiverView = (EditText) findViewById(R.id.receiver);
		mPhoneView = (EditText) findViewById(R.id.phone);
		mDistrictView = (TextView) findViewById(R.id.district);
		mAddressView = (EditText) findViewById(R.id.address);
		mZipCodeView = (EditText) findViewById(R.id.zipcode);
		findViewById(R.id.district_layout).setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_submit, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_submit:
			prepareSubmit();
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void prepareSubmit() {
		if (UiUtil.isFastDoubleClick())
			return;
		final String receiver = mReceiverView.getText().toString().trim();
		if (TextUtils.isEmpty(receiver)) {
			Toast.makeText(this, R.string.input_receiver_error, Toast.LENGTH_SHORT).show();
			return;
		}
		final String phone = mPhoneView.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			Toast.makeText(this, R.string.input_zip_code_error, Toast.LENGTH_SHORT).show();
			return;
		}
		final String district = mDistrictView.getText().toString().trim();
		if (TextUtils.isEmpty(district)) {
			Toast.makeText(this, R.string.input_district_error, Toast.LENGTH_SHORT).show();
			return;
		}
		final String address = mAddressView.getText().toString().trim();
		if (TextUtils.isEmpty(address)) {
			Toast.makeText(this, R.string.input_address_error, Toast.LENGTH_SHORT).show();
			return;
		}
		final String zipcode = mZipCodeView.getText().toString().trim();
		if (TextUtils.isEmpty(zipcode)) {
			Toast.makeText(this, R.string.input_zip_code_error, Toast.LENGTH_SHORT).show();
			return;
		}
		AccountManager accountManager = AccountManager.getInstance(getApplicationContext());
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		final UserTO user = accountManager.getUserTO();
		if (user.isExpired()) {
			Toast.makeText(this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
			LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		AlertDialog.Builder promptAlert = new AlertDialog.Builder(this);
		promptAlert.setTitle(R.string.prompt);
		promptAlert.setMessage(R.string.sure_about_exchange_info);
		promptAlert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				submit(receiver, phone, district, address, zipcode);
			}
		});
		promptAlert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		promptAlert.create().show();
	}

	private void submit(String receiver, String phone, String district, String address, String zipcode) {

		final ProgressDialog dialog = new ProgressDialog(this);
		dialog.setMessage(getString(R.string.submiting));
		dialog.setCancelable(false);
		dialog.show();
		String url = UriHelper.getExchangeGiftUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_GIFT_ID, String.valueOf(mGift.getId()));
		UserTO user = AccountManager.getInstance(getApplicationContext()).getUserTO();
		params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		params.put(UriHelper.PARAMS_TOKEN, user.getToken());
		params.put(UriHelper.PARAMS_PERSON, receiver);
		params.put(UriHelper.PARAMS_MOBILE, phone);
		params.put(UriHelper.PARAMS_ADDRESS, district + address);
		params.put(UriHelper.PARAMS_ZIPCODE, zipcode);
		GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				if (!hasDestroyed()) {
					dialog.dismiss();
					if (response == null) {
						Toast.makeText(getApplicationContext(), R.string.request_error, Toast.LENGTH_SHORT).show();
					} else {
						if (response.isSuccess()) {
							Intent data = new Intent();
							data.putExtra(Constants.EXTRA_DATA, mGift);
							setResult(RESULT_OK, data);
							finish();
						} else if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
							Toast.makeText(ExchangeGiftActivity.this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
							LoginActivity.start(ExchangeGiftActivity.this, -1, LoginActivity.ACTION_RETURN);
						} else {
							String msg = response.getMsg();
							msg = TextUtils.isEmpty(msg) ? getString(R.string.exchange_error) : msg;
							Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
						}
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					dialog.dismiss();
					Toast.makeText(getApplicationContext(), R.string.request_error, Toast.LENGTH_SHORT).show();
				}
			}
		}, params, BaseTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.district_layout:
			if (UiUtil.isFastDoubleClick())
				return;
			showProvinceDialog();
			break;
		default:
			break;
		}
	}

	protected void showProvinceDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.choose_district);
		builder.setAdapter(new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = View.inflate(getApplicationContext(), R.layout.city, null);
				}
				CityTO city = mCities.get(position);
				TextView cityView = ViewHolder.get(convertView, R.id.city);
				cityView.setText(city.getName());
				return convertView;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public Object getItem(int position) {
				return mCities == null ? null : mCities.get(position);
			}

			@Override
			public int getCount() {
				return mCities == null ? 0 : mCities.size();
			}

		}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				CityTO cityTO = mCities.get(which);
				showCityDialog(cityTO);
			}
		});
		builder.create().show();
	}

	private void showCityDialog(final CityTO province) {
		final List<CityTO> cities = province.getCities();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(province.getName());
		builder.setAdapter(new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = View.inflate(getApplicationContext(), R.layout.city, null);
				}
				CityTO city = cities.get(position);
				TextView cityView = ViewHolder.get(convertView, R.id.city);
				cityView.setText(city.getName());
				return convertView;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public Object getItem(int position) {
				return cities == null ? null : cities.get(position);
			}

			@Override
			public int getCount() {
				return cities == null ? 0 : cities.size();
			}

		}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				CityTO city = cities.get(which);
				onCityPicked(province, city);
			}
		});
		builder.create().show();
	}

	private void onCityPicked(CityTO province, CityTO city) {
		mDistrictView.setText(province.getName() + city.getName());
	}
}
